package app

import (
	"os"
	"path/filepath"
	"strings"

	Log "github.com/cihub/seelog"
	"gopkg.in/ini.v1"
)

// web项目基本配置信息
type WebConfigInfo struct {
	AppRoot string //程序根目录
	Root    string //页面根路径
	Port    string //端口
	Title   string //程序标题
	Name    string //名称
}

// 取对应配置
func (wf WebConfigInfo) Get() *WebConfigInfo {
	webConfigInfo := WebConfigInfo{}
	root := ""
	exePath, err := os.Executable()
	if err != nil {
		root = "."
	}

	root, _ = filepath.EvalSymlinks(filepath.Dir(exePath))

	webConfigInfo.AppRoot = strings.Replace(root, "\\", "/", -1)
	webConfigInfo.Port = "8080"
	webConfigInfo.Root = "/webroot/"
	webConfigInfo.Name = filepath.Base(exePath)
	webConfigInfo.Title = webConfigInfo.Name

	configFilePath := strings.Replace(root+"/config/app.ini", "\\", "/", -1)
	_, err = os.Stat(configFilePath) //os.Stat获取文件信息
	if err != nil {
		if !os.IsExist(err) {
			Log.Error("配置文件不存在", err)
			return &webConfigInfo
		}
	}

	cfg, err := ini.Load(configFilePath)
	if err != nil {
		Log.Error("配置文件读取错误", err)
		return &webConfigInfo
	}

	section := cfg.Section("System")
	webConfigInfo.Port = section.Key("Port").String()
	webConfigInfo.Name = section.Key("Name").String()
	webConfigInfo.Title = section.Key("Title").String()

	return &webConfigInfo
}

// 取开始运行提示信息
func (wf *WebConfigInfo) RunStartStr() string {
	var build strings.Builder
	build.WriteString("================ ")
	build.WriteString(wf.Title)
	build.WriteString(wf.Name)
	build.WriteString("启动完毕,使用端口:")
	build.WriteString(wf.Port)
	build.WriteString(" ================")

	return build.String()
}
